package net.keebook.webapp.ws;

import java.io.IOException;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;

import net.keebook.webapp.dao.SettingDao;
import net.keebook.webapp.dao.ShareRequestDao;
import net.keebook.webapp.entity.ShareRequest;
import net.keebook.webapp.model.SessionModel;
import net.keebook.webapp.util.SettingId;

import org.apache.log4j.Logger;


@Path("/join/{id}")
@Stateless
public class JoinKeebookService extends WebService {
	@EJB
	private SettingDao settingDao;
	@Inject
	private ShareRequestDao shareRequestDao;
	
	@GET
	public void saveSettings(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("id") String invitationId) throws IOException {
		String root = getSettingDao().get(SettingId.PUBLIC_URL).getValue();
		if (!root.endsWith("/")) {
			root += "/";
		}
		
		HttpSession httpSession = request.getSession(true);
		SessionModel sessionModel = SessionModel.getInstance(httpSession);
		
		ShareRequest sr = getShareRequestDao().get(invitationId);
		if (sr == null || sr.getKeeBook() == null || (sessionModel.getLoggedIn() && getKeeBookDao().canAccess(sessionModel.getUserId(), sr.getKeeBook().getId()))) {
			response.sendRedirect(root + "join-impossible.xhtml");
			return;
		}
		
		sessionModel.setInvitationId(invitationId);
		
		Logger.getLogger(this.getClass()).info("Processed join for id: " + invitationId);
		response.sendRedirect(root + "index.xhtml");
	}

	public SettingDao getSettingDao() {
		return settingDao;
	}

	public void setSettingDao(SettingDao settingDao) {
		this.settingDao = settingDao;
	}

	public ShareRequestDao getShareRequestDao() {
		return shareRequestDao;
	}

	public void setShareRequestDao(ShareRequestDao shareRequestDao) {
		this.shareRequestDao = shareRequestDao;
	}
}
